﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;
using System.IO;

namespace KnowledgeCommunity.Web.Controllers
{
    public class SliderController : Controller
    {
        SliderHelper mySliderHelper = new SliderHelper();
        //
        // GET: /Slider/

        public ActionResult Index()
        {
            var slider = mySliderHelper.FindAll();
            ViewData["sliderList"] = slider;
            return View();
        }

        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            string cont = Request.Form["s_cont"];
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-12-31");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }
            var sliders = mySliderHelper.SearchByKeyAndTime(title, cont, start, end);
            return View(sliders);

        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult List()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Slider> datesource = GetDataSource();//要分页的数据源
            Model.SliderList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.SliderList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Slider> GetDataSource()
        {
            var slider = mySliderHelper.FindAll();
            List<Slider> model = new List<Slider>();
            foreach (var item in slider)
            {
                model.Add(item);
            }
            return model;
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult PageIndex(Models.Page Model)
        {
            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Slider> datesource = GetDataSource();//要分页的数据源
            Model.SliderList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("List", Model);
            }
            //return View(Model);
        }

        public ActionResult Details(int id)
        {
            var _slider = mySliderHelper.FindById(id);
            return View(_slider);
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Create(Slider model)
        {
            string path = null;
            string fileOldName = null;
            string extension = null;
            string url = null;

            foreach (string image in Request.Files)
            {
                if (!HasFiles.HasFile(Request.Files[image]))
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"UpLoad\Sliders";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                string miniType = Request.Files[image].ContentType.ToLower();

                Stream fileStream = Request.Files[image].InputStream;

                //文件重命名
                string fileNewName = RandomNumber.RandomNumberToName() + extension;

                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));

                path = path + "\\" + fileNewName;
                url = "~\\UpLoad\\Sliders\\" + fileNewName;

            }
            model.ImgUrl = url;
            model.DelPath = path;
            model.Editor = HttpContext.User.Identity.Name;
            model.AddTime = DateTime.Now;

            bool n = mySliderHelper.Create(model);
            if (n)
                return RedirectToAction("List");
            else
            {
                //回滚操作！
                System.IO.File.Delete(path);
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Edit(int id)
        {
            var _slider = mySliderHelper.FindById(id);
            return View(_slider);
        }

        [ValidateInput(false)]
        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Edit(Slider model)
        {
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Delete(int id)
        {
            var _slider = mySliderHelper.FindById(id);
            return View(_slider);
        }

        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = mySliderHelper.Delete(id);
            if (n)
                return RedirectToAction("List", "Slider");
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        CKCDB mydb = new CKCDB();

        private void DoUpdateModel(Slider model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Sliders.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Sliders>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }


    }
}
